//
//  JokeDataManager.m
//  Diary
//
//  Created by lanou3g on 15/12/22.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "JokeDataManager.h"
#import "Model.h"
static JokeDataManager *handel = nil;
@implementation JokeDataManager

+ (JokeDataManager *)sharedDataManager{
    
    
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (handel == nil) {
             handel = [super allocWithZone:zone];
        }
    });
    
    return handel;
}


- (void)getDataFromNetwithStr:(int)count Block:(JokeBlock)finishBlock{
    

    NSString *string = [NSString stringWithFormat:@"http://v.juhe.cn/weixin/query?key=8bc95c0ed38df2aebf5a149fed1701d1&ps=100&pno=%d",count];
    
    NSURL *url = [NSURL URLWithString:string];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    //发送
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        @autoreleasepool {
            
            if (data == nil || error != nil) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    finishBlock(NO);
                    return ;
                });
                
                
                
            }
            if (data == nil) {
                return ;
            }
            
            else{
            //解析数据
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            NSDictionary *dict = resultDic[@"result"];
            
            NSArray *array = dict[@"list"];
            
           
            NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:10];
            
            for (NSDictionary *dic in array) {
                Model *model = [[Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [array1 addObject:model];
                
            }
            
            self.jokeDataArray = [NSArray arrayWithArray:array1];
                
        }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (self.jokeDataArray.count > 0) {
                    finishBlock(YES);
                }else{
                    
                    finishBlock(NO);
                }
                
            });
            
            

        }
        
    }];
    
    //开始任务
    [dataTask resume];
    
}



    
    






@end
